package com.zengqingfa.juc.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * @fileName: Test4
 * @author: zengqf3
 * @date: 2021-6-10 11:11
 * @description:
 */
@Slf4j(topic = "c.Test4")
public class Test4 {

    ArrayList<String> list = new ArrayList<>();

    public void method1(int loopNumber) {
        for (int i = 0; i < loopNumber; i++) {
            // { 临界区, 会产生竞态条件
            method2();
            method3();
            // } 临界区
        }
    }

    private void method2() {
        list.add(Thread.currentThread().getName() + "-1");
    }

    private void method3() {
        list.remove(0);
    }

    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 200;

    public static void main(String[] args) {
        Test4 test = new Test4();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + i).start();
        }
    }
}
